import React, {PureComponent, Fragment} from 'react';
import {connect} from 'dva';
import moment from 'moment';
import {routerRedux, Link} from 'dva/router';
import {
    Row,
    Col,
    Card,
    Form,
    Input,
    Select,
    Icon,
    Button,
    Dropdown,
    Menu,
    InputNumber,
    DatePicker,
    Modal,
    message,
    Checkbox,
    Popconfirm,
    Divider,
    Table,
    Badge,
} from 'antd';
import PageHeaderLayout from '../../layouts/PageHeaderLayout';
import defaultAvatar from '../../assets/admin_logo.png';
import styles from './Banner.less';
import EditTableCell from './EditTableCell';

const FormItem = Form.Item;
const {Option} = Select;
const getValue = obj =>
    Object.keys(obj)
        .map(key => obj[key])
        .join(',');
const statusMap = ['default', 'processing', 'success', 'error'];
const status = ['关闭', '运行中', '已上线', '异常'];

const CreateForm = Form.create()(props => {
    const {modalVisible, form, handleAdd, handleModalVisible} = props;
    const okHandle = () => {
        form.validateFields((err, fieldsValue) => {
            if (err) return;
            form.resetFields();
            handleAdd(fieldsValue);
        });
    };
    return (
        <Modal
            title="新建规则"
            visible={modalVisible}
            onOk={okHandle}
            onCancel={() => handleModalVisible()}
        >
            <FormItem labelCol={{span: 5}} wrapperCol={{span: 15}} label="描述">
                {form.getFieldDecorator('desc', {
                    rules: [{required: true, message: 'Please input some description...'}],
                })(<Input placeholder="请输入"/>)}
            </FormItem>
        </Modal>
    );
});

@connect(({indexBanner, loading}) => ({
    indexBanner,
    loading: loading.models.indexBanner,
}))
@Form.create()
export default class TableList extends PureComponent {
    state = {
        modalVisible: false,
        expandForm: false,
        selectedRows: [],
        formValues: {},
        addInputValue: '',
        checkedGroupList: [],
    };

    componentDidMount() {
        const {dispatch} = this.props;
        dispatch({
            type: 'indexBanner/fetch',
        });
    }

    bindDelete = (id)=> {
        this.props.dispatch({
            type: 'indexBanner/deleteItem',
            payload: {
                id: id
            }
        }).then(res=> {
            if (res) {
                message.success('删除成功');
            } else {
                message.error('删除失败');
            }
        })
    };

    onCellChange = (key, dataIndex) => {
        return (value) => {
            console.log(value);
            if (isNaN(value)) {
                message.error('权重必须为0-100的数值');
                return false;
            } else if (Number(value) > 100 || Number(value) < 0) {
                message.error('权重必须为0-100的数值');
                return false;
            }
            this.props.dispatch({
                type: 'indexBanner/changeWeight',
                payload: {
                    id: key,
                    dataIndex,
                    value: Number(value),
                }
            });
        };
    };
    changeStatus = (item)=> {
        const {id, status} = item;
        console.log('item', item);
        this.props.dispatch({
            type: 'indexBanner/changeStatus',
            payload: {
                id,
                status: status ? 0 : 1
            }
        })
    };

    render() {
        console.log(this.props);
        const {indexBanner : {data}, loading} = this.props;
        const {selectedRows, modalVisible, addInputValue, checkedGroupList} = this.state;
        const columns = [
            {
                title: 'ID',
                dataIndex: 'id',
                width: 60,
            },
            {
                title: '标题',
                dataIndex: 'title'
            },
            {
                title: '描述',
                dataIndex: 'desc'
            },
            {
                title: '图片',
                dataIndex: 'img',
                render: val=> {
                    return <img src={val || defaultAvatar} width="100" height={60}/>
                }
            },
            {
                title: '链接地址',
                dataIndex: 'url',
                width: 200
            },
            {
                title: '权重',
                dataIndex: 'weight',
                render: (val, record) => {
                    return <EditTableCell
                        value={val}
                        onChange={this.onCellChange(record.id, 'weight')}
                    />
                }
            },
            {
                title: '状态',
                dataIndex: 'status',
                render: (val) => {
                    return <Badge status={val ? 'success' : 'error'} text={val ? '已上架' : '已下架'}/>
                }
            },
            {
                title: '操作',
                width: 150,
                render: (text, record) => (
                    <Fragment>
                        <Popconfirm title="你确定删除？" okText="确定" cancelText="取消" onConfirm={()=> {
                            this.bindDelete(record.id)
                        }}>
                            <a href="">删除</a>
                        </Popconfirm>
                        <Divider type="vertical"/>
                        <a href="javascript:;" onClick={ ()=> {
                            this.changeStatus(record)
                        } }>{record.status ? '下架' : '上架'}</a>
                        <Divider type="vertical"/>
                        <Link to={`/index/banner-save?id=${record.id}`}>修改</Link>
                    </Fragment>
                ),
            },
        ];

        return (
            <div>
                <Card bordered={false}>
                    <div className={styles.tableListOperator}>
                        <Button>
                            <Link to={`/index/banner-save`}>
                                新建
                            </Link>
                        </Button>
                    </div>
                    <div className={styles.tableList} style={{marginTop: '16px'}}>
                        <Table columns={columns} dataSource={data} loading={loading} rowKey="id"/>
                    </div>
                </Card>
            </div>
        );
    }
}
